package com.renshine.swing.model;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableColumn;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.renshine.base.service.QueryService;
import com.renshine.swing.listener.TBKeyAdapter;

/**
 * 列表 - 表格模型
 * 
 * @author deyang
 *
 */
@Component
@SuppressWarnings("serial")
public class ListTableModel extends BaseTableModel {

	@Autowired
	QueryService service;
	
	/** 列对应的标题数组 */
	private final static Object[] COLUMN_NAMES = {"字段名", "类型", "说明","宽度" };

	/** 列宽比例 */
	public static Object[] WIDTH_PERCENTAGE = { " ", "3%", "5%", "8%", "10%",
			"15%", "20%", "25%", "30%" };

	public ListTableModel() {
		super(COLUMN_NAMES, 0);
	}

	/**
	 * 重载了DefaultTableModel的addRow方法
	 * 
	 * @param rowData 新添加的数据
	 */
	@Override
	public void addRow(Object[] rowData) {
		if (!existed(rowData, new int[] { 0 })) {
			super.addRow(rowData);
		}
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public JSplitPane createJSplit(final String tbName) {
		final BaseTableModel model = new ListTableModel();
		// 表选择监听器
		final JList<String> jlist = new JList<String>();
    	jlist.setListData(service.queryFdNames(tbName));
    	jlist.addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent e) {
				if(e.getValueIsAdjusting()){							
					String[] fdNames = jlist.getSelectedValuesList().toArray(new String[]{});
					model.addLotRow(service.fieldListRowDatas(tbName, fdNames));
					
				}
			}
		});
    	
    	// table删除,移动响应监听器
    	JTable table = new JTable(model);
    	table.addKeyListener(new TBKeyAdapter(table, model));
    	
    	// 控件丰富化
    	TableColumn valColumn = table.getColumn(COLUMN_NAMES[3]);
		JComboBox box = new JComboBox(WIDTH_PERCENTAGE);
		box.setEditable(true);// 设置可编辑
		valColumn.setCellEditor(new DefaultCellEditor(box));

    	// 分割pane
    	JSplitPane jsplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,new JScrollPane(jlist), new JScrollPane(table));
    	jsplit.setDividerSize(4);
		jsplit.setDividerLocation(150);
		
		return jsplit;
	}
}
